package com.ww.learn.coroutine.actors

import kotlinx.coroutines.*
import kotlinx.coroutines.channels.SendChannel
import kotlinx.coroutines.channels.actor

fun CoroutineScope.counterActor(): SendChannel<CounterMessage> = actor<CounterMessage> {
    var counter = 0 // 内部状态（仅Actor自身可修改，天然线程安全）

    // 循环接收消息并处理（Actor的核心逻辑）
    for (message in channel) {
        when (message) {
            is Increment -> counter++
            is Decrement -> counter--
            is GetValue -> message.response.complete(counter) // 通过response回传结果
        }
    }
}

fun main(): Unit = runBlocking {
    val counter = counterActor() // 创建计数器Actor

    repeat(100) {
        launch(Dispatchers.IO) {
            // 每个协程随机发送10次递增/递减消息
            repeat(10) {
                if (it % 2 == 0) counter.send(Increment)
                else counter.send(Decrement)
            }
        }
    }

    // 等待所有并发操作完成
    delay(1000)

    // 获取最终结果
    val result = CompletableDeferred<Int>()
    counter.send(GetValue(result))
    println("最终计数：${result.await()}")

    // 关闭actor
    counter.close()
}